package main

import (
	"crypto/md5"
	"fmt"
	"io"
	"net/http"
	"os"
	"time"
)

func main() {
	start := time.Now()
	ch := make(chan string)
	for _, url := range os.Args[1:] {
		go fetchTwice(url, ch)
	}
	for range os.Args[1:] {
		fmt.Println(<-ch)
		fmt.Println(<-ch)
	}
	fmt.Printf("%.2fs   elapsed\n", time.Since(start).Seconds())
}

func fetchTwice(url string, ch chan<- string) {
	start1 := time.Now()
	resp1, err := http.Get(url)
	if err != nil {
		ch <- fmt.Sprint(err)
		return
	}
	body1, err := io.ReadAll(resp1.Body)
	if err != nil {
		ch <- fmt.Sprint(err)
		return
	}

	//计算哈希值
	hash1 := fmt.Sprintf("%x", md5.Sum(body1))
	secs1 := time.Since(start1).Seconds()
	ch <- fmt.Sprintf("%.2fs    %s : %v", secs1, url, hash1)

	//第二次请i去
	start2 := time.Now()
	resp2, err := http.Get(url)
	if err != nil {
		ch <- fmt.Sprint(err)
		return
	}
	body2, err := io.ReadAll(resp2.Body)
	if err != nil {
		ch <- fmt.Sprint(err)
		return
	}

	//计算哈希值
	hash2 := fmt.Sprintf("%x", md5.Sum(body2))
	secs2 := time.Since(start2).Seconds()
	ch <- fmt.Sprintf("%.2fs    %s : %v", secs2, url, hash2)
}
